package initial

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

// 响应JSON
type Response struct {
	Code int            `json:"code"`
	Msg  string         `json:"msg"`
	Data map[string]any `json:"data"`
}

// go 原生构建http请求
func Init() {
	//注册路由,get,post,put,delete等所有请求都会进来这里
	http.HandleFunc("/index", Index)
	//
	fmt.Println("start server")
	//创建一个http服务器
	http.ListenAndServe("127.0.0.1:8080", nil)
}

func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.Method, r.URL.String())
	if r.Method != "GET" {
		byteData, _ := io.ReadAll(r.Body)
		fmt.Println(string(byteData))
	}
	//请求头
	fmt.Println(r.Header)

	jsonStr, _ := json.Marshal(Response{Code: 200, Msg: "success", Data: map[string]any{}})

	w.Write(jsonStr)

}
